/*
 * @Author: yuliang
 * @Date: 2020-08-20 14:07:42
 * @LastEditors: kanglang
 * @LastEditTime: 2021-04-28 18:52:52
 * @Description: 车主端/运单列表
 */

import React from 'react';
import {
  View,
  StyleSheet,
  Image,
  Text,
  NativeModules,
  Linking,
  Modal,
  SafeAreaView,
  TouchableOpacity,
  ActivityIndicator,
  InteractionManager
} from 'react-native';
import { iconWayOrderCoffee, iconWayOrderGray, iconDriverUser, leftBack } from '@/images';
import { BackImage, msg, XMHeader } from '@/common';
import {
  fontColorBlack,
  isAndroid,
  mainBgColorLightGray,
  fontColorDeepRed,
  mainBgColorWhite,
  screenWidth,
  screenHeight,
  px2dp
} from '@/styles';
import DashLine from '@/common/dashLine';
// import ImageViewer from '../../../components/XmImageViewer';
import { isIphoneX } from '@/common/util';

import supply from '@/api/supply';
import Picker from '@/common/picker';
import tool from '@/common/getDate';
import { fetchUnitList } from '@/api/source-release';
import TypeAssemble from '../../../components/type-assemble';
import OrderStatus from '../../../components/order_status';
import XmList from '../../../components/XmList';
import HeadTabs from '../../../components/HeadTabs';

export default class CarOwnerOrder extends React.Component {
  static navigationOptions = () => ({
    title: '运单',
    tabBarIcon: ({ focused }) => (
      <Image
        source={focused ? iconWayOrderCoffee : iconWayOrderGray}
        style={{ width: 24, height: 24 }}
      />
    ),
  });

  constructor(props) {
    super(props);
    this.state = ({
      status: -1,
      // 数据源
      productOrderList: [],
      pageNo: 1,
      pageSize: 10,
      isLoading: false,
      total: 0,
      showFoot: 1, // 控制foot， 0：隐藏footer  1：已加载完成,没有更多数据   2 ：显示加载中
      modalVisible: false,
      transparent: true,
      previewModal: false,
      previewLabel: '',
      previewAdress: '',
      images: [],
      tabSources: [
        {
          tab: '全部',
          type: -1,
          corlor: '#000',
          rightIcon: require('../../../images/wl/icon_right_gray.png')
        },
        {
          tab: '未完成',
          type: 1,
          corlor: '#EB2F2F',
          rightIcon: require('../../../images/wl/icon_right_red.png')
        },
        // {
        //   tab: '待装货',
        //   type: 0,
        //   corlor: '#EB2F2F',
        //   rightIcon: require('../../../../image/wl/icon_right_red.png')
        // }, {
        //   tab: '运输中',
        //   type: 1,
        //   corlor: '#BA914A',
        //   rightIcon: require('../../../../image/wl/icon_right_origre.png')
        // }, {
        //   tab: '已送达',
        //   type: 2,
        //   corlor: '#2CBD26',
        //   rightIcon: require('../../../../image/wl/icon_right_green.png')
        // },
        {
          tab: '已完成',
          type: 2,
          corlor: '#999896',
          rightIcon: require('../../../images/wl/icon_right_gray.png')
        }
      ],
      stateSources: [
        {
          tab: '全部',
          type: -1,
          corlor: '#000',
          rightIcon: require('../../../images/wl/icon_right_gray.png')
        },
        {
          tab: '未完成',
          type: 1,
          corlor: '#EB2F2F',
          rightIcon: require('../../../images/wl/icon_right_red.png')
        },
        {
          tab: '已完成',
          type: 2,
          corlor: '#999896',
          rightIcon: require('../../../images/wl/icon_right_gray.png')
        },
        // {
        //   tab: '待装货',
        //   type: 0,
        //   corlor: '#EB2F2F',
        //   rightIcon: require('../../../../image/wl/icon_right_red.png')
        // }, {
        //   tab: '运输中',
        //   type: 1,
        //   corlor: '#BA914A',
        //   rightIcon: require('../../../../image/wl/icon_right_origre.png')
        // }, {
        //   tab: '已送达',
        //   type: 2,
        //   corlor: '#2CBD26',
        //   rightIcon: require('../../../../image/wl/icon_right_green.png')
        // }, {
        //   tab: '已完成',
        //   type: 3,
        //   corlor: '#999896',
        //   rightIcon: require('../../../../image/wl/icon_right_gray.png')
        // }, {
        //   tab: '已作废',
        //   type: -2,
        //   corlor: '#999896',
        //   rightIcon: require('../../../../image/wl/icon_right_gray.png')
        // }
      ],
      // 车主拥有的车辆
      carNoList: [],
      carNo: '全部车辆',
      unitList: [],
    });
  }

  choosePutCar = () => {
    let that = this;
    Picker.init({
      pickerTitleText: '选择',
      pickerCancelBtnText: '取消',
      pickerConfirmBtnColor: [186, 145, 74, 1],
      pickerCancelBtnColor: [102, 101, 100, 1],
      pickerConfirmBtnText: '确定',
      selectedValue: [
        this.state.carNo
      ],
      pickerBg: [255, 255, 255, 1],
      pickerToolBarBg: [255, 255, 255, 1],
      pickerFontColor: [186, 145, 74, 1],
      pickerRowHeight: 40,
      pickerData: that.state.carNoList,
      onPickerConfirm: (pickedValue, pickedIndex) => {
        console.log(pickedValue);
        this.setState({
          carNo: pickedValue[0]
        }, () => {
          this.loadData();
        });
      },
      onPickerCancel: (pickedValue, pickedIndex) => {
        console.log('date', pickedValue, pickedIndex);
      },
      onPickerSelect: (pickedValue, pickedIndex) => {
        console.log('date', pickedValue, pickedIndex);
      },
    });
    Picker.show();
  };

  componentDidMount() {
    console.log('车主端运单');
    this.fetchUnitList();
    InteractionManager.runAfterInteractions(() => {
      this.loadData();
      this.getCar();
    });
  }

  // 获取车主拥有的车辆
  getCar = () => {
    supply.getCarNew().then(res => {
      console.log('车主车辆======>', res.data);

      // let listArr;
      // listArr = ['全部车辆', ...res.data];
      // this.setState({
      //   carNoList: listArr
      // });
      let carList = [];
      if (res.success) {
        res.data.forEach(v => {
          carList.push(v.carNo);
        });
        carList.unshift('全部车辆');
        this.setState({
          carNoList: carList
        });
      } else {
        msg.emit('app:tip', { text: '网络错误' });
      }
    }).catch(err => {
      msg.emit('app:tip', { text: '网络错误' });
    });
  }

  fetchUnitList = (status) => {
    fetchUnitList({ status }).then((res) => {
      if (res.success) {
        let unitOptionsObj = {};
        res.data.forEach(item => {
          unitOptionsObj[item.code] = item.name;
        });
        this.setState({ unitList: unitOptionsObj });
      } else {
        msg.emit('app:tip', { text: '遇到网络错误，请重试' });
      }
    });
  };

  // 初始化列表数据
  initList = (state, pageNo, carNo, pageSize, type) => {
    if (carNo == '全部车辆') {
      carNo = '';
    }
    console.log('-------------', this.state.productOrderList);
    console.log('-------------', state, pageNo, carNo, pageSize, type);
    supply.pageCarOwnerWaybillDriver({
      status: state,
      // status: 1,
      identity: 2,
      pageNo: pageNo || 1,
      carNo: carNo,
      pageSize: pageSize
    }).then(res => {
      let list = this.state.productOrderList;
      const newList = res.data.list;
      console.log('newList');
      console.log(newList);
      if (res.success) {
        res.data.list.forEach(ele => {
          if (ele.loadingBeginTime == '' || ele.loadingEndTime == '') {
            ele.time = '-';
          } else {
            ele.time = `${tool.dateForm(new Date(ele.loadingBeginTime.replace(/\-/g, '/')), 'MM-dd hh:mm')} - ${
              tool.dateForm(new Date(ele.loadingEndTime.replace(/\-/g, '/')), 'hh:mm')}`;
          }
        });

        if (res.data.total == 0) {
          this.setState({
            isLoading: false,
            showFoot: 0
          });
          return;
        }
        if (res.data.list.length <= 0) {
          this.setState({
            isLoading: false,
            showFoot: 1
          });
          return;
        }

        if (type == 'dropdown') {
          this.setState({ isLoading: false });
          list = newList.concat(list);
        } else if (type == 'pullMore') {
          list = list.concat(newList);
        }
        console.log('list数据', list);
        this.setState({
          pageNo: this.state.pageNo + 1,
          productOrderList: list
        });
        if (res.data.list.length <= this.state.pageSize) {
          this.setState({
            isLoading: false,
            showFoot: 1
          });
        }
      } else {
        msg.emit('app:tip', { text: '网络错误' });
        this.setState({
          isLoading: false,
          showFoot: 0
        });
      }
    }).catch(err => {
      // msg.emit('app:tip', { text: "网络错误" });
      this.setState({
        isLoading: false,
        showFoot: 0
      });
    });
  }

  changeStatus(status) {
    console.log('改变状态------------->', status);
    this.setState({
      status,
      pageNo: 1,
      productOrderList: []
    }, () => {
      InteractionManager.runAfterInteractions(() => {
        this.loadData();
      });
    });
  }

  // 下拉刷新
  loadData = () => {
    this.setState({
      isLoading: true,
      pageNo: 1,
      productOrderList: []
    }, () => {
      const { status, pageNo, carNo, pageSize } = this.state;
      this.initList(status, pageNo, carNo, pageSize, 'dropdown');
    });
  }

  // 加载更多
  LoadMore = () => {
    const { pageSize, status, pageNo, carNo } = this.state;
    this.setState({
      showFoot: 2
    }, () => {
      InteractionManager.runAfterInteractions(() => {
        this.initList(status, pageNo, carNo, pageSize, 'pullMore');
      });
    });
  }

  toDetail = (data) => {
    msg.emit('router: goToNext', {
      routeName: 'CarOrderDetail',
      businessNo: data.transportNo,
      plat: 2 // 1  货主端   2车主端  3 司机端
    });
    // msg.emit('router: goToNext', {
    //   routeName: 'WaybillDetails',
    //   businessNo: data.transportNo,
    //   plat: 2   // 1  货主端   2车主端  3 司机端
    // });
  }

  // 每个运单item的状态
  loadState = (state) => {
    // let arr = ['-2','-1', '0', '1', '2', '3']
    let arr = ['-1', '1', '2'];
    if (arr.indexOf(String(state)) !== -1) {
      return this.state.stateSources.filter(ele => ele.type == state)[0];
    }
    return { corlor: '', tab: '' };
  }

  // 接收地址信息
  addrDetails = (addr) => {
    if (addr) {
      const xmCity = (addr.province === '北京市' || addr.province === '天津市' || addr.province === '重庆市' || addr.province === '上海市') ?
        addr.province :
        addr.city;
      return xmCity + addr.district + (addr.addressDetails ? addr.addressDetails : '');
    }
    return '';
  }

  render() {
    const { status, productOrderList, isLoading, showFoot, modalVisible, transparent, previewModal, previewLabel, previewAdress, tabSources, unitList } = this.state;

    const renderItem = ({ item }) => {
      return (
        <View style={styles.itemWrap}>
          <View>
            <View style={styles.itemTop}>
              <Text style={styles.topIime}>
                {item.loadingBeginTime.substr(5, item.loadingBeginTime.length - 8)}
                {' '}
                -
                {' '}
                {item.loadingEndTime.substr(5, item.loadingEndTime.length - 8)}
                可装货
              </Text>
              <OrderStatus
                textColor={this.loadState(item.transportStatus).corlor}
                rightIcon={this.loadState(item.transportStatus).rightIcon}
                statusText={this.loadState(item.transportStatus).tab}
              />
            </View>
            <DashLine style={styles.dashStyle} />
            <TouchableOpacity onPress={() => this.toDetail(item)}>
              <View style={styles.startWrap}>
                <Image style={styles.startIcon} source={require('../../../images/icons/icon_start_point_green.jpg')} resizeMode='stretch' />
                <View style={{ width: '95%' }}>
                  <Text numberOfLines={1} style={[styles.adress]}>{item.startAddress}</Text>
                </View>
              </View>
              <View style={styles.parames}>
                <TypeAssemble
                  lineData={[item.goodsName, item.packageName, item.weight + unitList[item.weightUnit]]}
                />
              </View>
              <View style={styles.startWrap}>
                <View style={styles.startIconWrap}>
                  <Image style={styles.startIcon} source={require('../../../images/icons/icon_end_point_orange.jpg')} />
                </View>
                <View style={{ width: '93%' }}>
                  <Text numberOfLines={1} style={[styles.adress]}>{item.endAddress}</Text>
                </View>

              </View>
              <View style={styles.user}>
                <View style={styles.userItem}>
                  <View style={styles.userWrap}>
                    <Image
                      style={styles.startIcon}
                      source={iconDriverUser}
                    />
                    <Text>{item.driverName}</Text>
                  </View>
                  <View style={styles.userWrap}>
                    <Image style={styles.startIcon} source={require('../../../images/icons/icon_truck_gray.png')} />
                    <Text>{item.carNo}</Text>
                  </View>
                </View>
              </View>
              <DashLine style={styles.dashStyle} />
            </TouchableOpacity>
            <View style={styles.linkWrap}>
              <View style={styles.priceWrap}>
                <Text style={{}}>
                  <Text style={{ color: fontColorDeepRed, fontSize: px2dp(24) }}>¥ </Text>
                  <Text style={{ color: fontColorDeepRed, fontSize: px2dp(36) }}>
                    {item.amountPer}
                    /
                    {unitList[item.weightUnit]}
                  </Text>
                </Text>
              </View>
            </View>
          </View>
        </View>

      );
    };

    return (
      <SafeAreaView>
        <XMHeader
          title='我的运单'
          renderLeft={() => { return (<></>); }}
          renderRight={() => {
            return (
              <TouchableOpacity
                activeOpacity={0.8}
                style={{ marginRight: 14 }}
                onPress={() => {
                  this.choosePutCar();
                }}
              >
                <View style={{ marginHorizontal: 6, flexDirection: 'row', alignItems: 'center' }}>
                  <Text style={{ marginRight: px2dp(4) * 2 }}>{this.state.carNo}</Text>
                  <Image style={{ width: px2dp(10) * 2, height: px2dp(6.5) * 2 }} resizeMode='contain' source={require('../../../images/wl/icon_down.png')} />
                </View>
              </TouchableOpacity>
            );
          }}
        />
        <View style={styles.container}>
          <HeadTabs
            tabSources={tabSources}
            changeStatus={(type) => this.changeStatus(type)}
            status={status}
          />
          <XmList
            sources={productOrderList}
            renderItem={renderItem}
            isLoading={isLoading}
            onDropdownRefresh={() => this.loadData()}
            onPullUpMore={() => this.LoadMore()}
            singleKey={item => item.id}
            showFoot={showFoot}
          />

        </View>

      </SafeAreaView>
    );
  }

  renderLoad() { // 这里是写的一个loading
    return (
      <View style={{ marginTop: (screenHeight / 2) - 20 }}>
        <ActivityIndicator size='large' />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    height: '100%',
    width: '100%',
    backgroundColor: mainBgColorLightGray,
    paddingBottom: px2dp(40)
  },
  closeWrap: {
    flexDirection: 'row',
    justifyContent: 'flex-end'
  },
  modalContent: {
    alignItems: 'center'
  },
  modalTip: {
    paddingTop: px2dp(50),
    paddingBottom: px2dp(50)
  },
  closeBtn: {
    width: px2dp(24),
    height: px2dp(24)
  },
  modealBtnWrap: {
    flexDirection: 'row'
  },
  mask: {
    width: screenWidth,
    height: screenHeight,
    backgroundColor: 'rgba(0,0,0,0.2)',
    justifyContent: 'center',
    alignItems: 'center'
  },
  modalMain: {
    width: '70%',
    padding: px2dp(20),
    borderRadius: px2dp(10),
    backgroundColor: mainBgColorWhite
  },
  modalBox: {
    width: '100%',
    height: '100%',
    backgroundColor: '#000000',
    opacity: 0.4,

  },
  linkWrap: {
    flexDirection: 'row',
    justifyContent: 'flex-end'
  },
  dashStyle: {
    marginTop: px2dp(24),
    marginBottom: px2dp(24),
  },
  telBtn: {
    paddingTop: px2dp(8),
    paddingBottom: px2dp(8),
    paddingLeft: px2dp(10),
    paddingRight: px2dp(10),
    borderWidth: px2dp(1),
    borderColor: '#CDCCC9',
    color: '#999896',
    borderRadius: px2dp(5),
    marginLeft: px2dp(20)
  },
  sureBtn: {
    borderColor: '#BA914A',
    color: '#BA914A',
  },
  modelSure: {
    backgroundColor: '#f59a23',
    paddingTop: px2dp(6),
    paddingBottom: px2dp(6),
    paddingLeft: px2dp(10),
    paddingRight: px2dp(10),
    color: mainBgColorWhite,
    borderWidth: px2dp(1),
    borderColor: '#f59a23',
  },
  modelCancel: {
    borderWidth: px2dp(1),
    borderColor: '#f59a23',
    color: '#f59a23',
    paddingTop: px2dp(6),
    paddingBottom: px2dp(6),
    paddingLeft: px2dp(10),
    paddingRight: px2dp(10),
    marginRight: px2dp(60)
  },
  itemWrap: {
    marginHorizontal: px2dp(20),
    marginTop: px2dp(24),
    padding: px2dp(20),
    borderRadius: px2dp(10),
    backgroundColor: mainBgColorWhite
  },
  itemTop: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between'
  },
  topIime: {
    color: '#999896',
    fontSize: px2dp(26)
  },
  orderStatus: {
    fontSize: px2dp(28)
  },
  startWrap: {
    flexDirection: 'row',

  },
  adress: {
    color: '#343332',
    fontSize: px2dp(32),
    fontWeight: '500',
    marginLeft: px2dp(12),

  },
  startWrap: {
    flexDirection: 'row',
    alignItems: 'center'
  },
  startIcon: {
    width: px2dp(36),
    height: px2dp(36),
    marginRight: px2dp(8),
  },
  shuxian: {
    borderLeftColor: '#CDCCC9',
    borderLeftWidth: px2dp(1),
    borderRightColor: '#CDCCC9',
    borderRightWidth: px2dp(1),
    marginLeft: px2dp(10),
    marginRight: px2dp(10),
    paddingLeft: px2dp(10),
    paddingRight: px2dp(10)
  },
  parames: {
    marginLeft: px2dp(54),
    marginTop: px2dp(16),
    paddingBottom: px2dp(12),
    flexDirection: 'row'
  },
  user: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    marginTop: px2dp(24),
  },
  userItem: {
    flexDirection: 'row',
    alignItems: 'center',
    width: '100%',
    flexWrap: 'wrap'
  },
  userWrap: {
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: '#F5F5F5',
    padding: px2dp(6) * 2,
    marginRight: px2dp(20) * 2,
    borderRadius: px2dp(5) * 2,
    marginBottom: px2dp(10) * 2
  },
  priceWrap: {
    flexDirection: 'row',
    alignItems: 'flex-end',
  },
  price: {
    fontSize: px2dp(20) * 2,
    color: '#333232'
  },
  color: {
    color: '#333232'
  },
  viewerStyle: {
    bottom: px2dp(24) * 2,
    flexDirection: 'row'
  },
  commonText: {
    color: mainBgColorWhite,
    fontSize: px2dp(14) * 2
  },
  textOne: {
    width: '20%',
    textAlign: 'left',
    paddingLeft: px2dp(16) * 2
  },
  textTwo: {
    width: '80%',
    textAlign: 'right',
    paddingRight: px2dp(16) * 2
  },
  leftBack: {
    width: px2dp(20) * 2,
    height: px2dp(20) * 2
  },
  backBtn: {
    paddingLeft: px2dp(12) * 2,
    paddingRight: px2dp(12) * 2,
    top: isIphoneX ? px2dp(40) * 2 : px2dp(20) * 2,
    position: 'absolute',
    zIndex: 1000
  }
});
